﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using DLM.Domain.Model;
using DLM.Services.Interfaces;
using DLM.Web.ViewModel.Admin;
using DLM.Web.ViewModel;
using DLM.Infrastructure.Configuration;
using DLM.Services.BonusRule;
using DLM.Web.MVC.Extensions;
using System.Xml.Linq;
using System.Configuration;
using System.IO;
using System.Web.Configuration;
using DLM.Infrastructure.Imaging;

namespace DLM.Web.MVC.Areas.Management.Controllers
{
    [AdminAuthorize]
    public class PartyController : Controller
    {
        private IPartyService partyService;
        private IUserService userService;
        private IScheduleService scheduleService;

        public PartyController(IPartyService partyService, IUserService userService, IScheduleService scheduleService)
        {
            this.partyService = partyService;
            this.userService = userService;
            this.scheduleService = scheduleService;
        }

        //
        // GET: /Management/Party/

        [HttpGet]
        public ActionResult List(int? page)
        {
            ViewData["PartyType"] = this.partyService.GetPartyType();
            var list = this.partyService.GetParty(PartyStatus.PendingForApproval, page ?? 0, 15);
            return View(list);
        }

        [HttpGet]
        public ActionResult RefusedList(int? page)
        {
            ViewData["PartyType"] = this.partyService.GetPartyType();
            var list = this.partyService.GetParty(PartyStatus.Cancel, page ?? 0, 15);
            return View(list);
        }


        public ActionResult ApprovedList(int? page)
        {
            ViewData["PartyType"] = this.partyService.GetPartyType();
            var list = this.partyService.GetParty(PartyStatus.Open, page ?? 0, 15);
            return View(list);
        }

        [HttpGet]
        public ActionResult FreezeList(int? page)
        {
             ViewData["PartyType"] = this.partyService.GetPartyType();
            var list = this.partyService.GetParty(PartyStatus.Freeze, page ?? 0, 15);
            return View(list);
        }

        [HttpGet]
        public ActionResult ClosedList(int? page)
        {
             ViewData["PartyType"] = this.partyService.GetPartyType();
            var list = this.partyService.GetParty(PartyStatus.Closed, page ?? 0, 15);
            return View(list);
        }


        [HttpGet]
        public ActionResult Edit(int? id)
        {
            var party = this.partyService.GetParty(id ?? 0);
            var userList = this.userService.Participated(id ?? 0, 0, 15);
            var remarkList = this.partyService.GerRemarkByParty(id ?? 0, 0, 15);
            var album = this.partyService.GetPartyAlbum(id ?? 0, 0, 8);
            PartyInfoPageView partyView = new PartyInfoPageView();
            partyView.Party = party;
            partyView.UserList = userList;
            partyView.RemarkList = remarkList;
            partyView.Album = album;
            return View(partyView);
        }

        [HttpPost]
        public ActionResult Edit(FormCollection collection)
        {
            var partyID = int.Parse(collection["Party.PartyID"].ToString());
            var currentParty = this.partyService.GetParty(partyID);
            currentParty.Status = int.Parse(collection["Party.Status"].ToString());
            if (collection["Party.IsSuccess"] != null)
            {
                currentParty.IsSuccess = bool.Parse(collection["Party.IsSuccess"].ToString()); 
                //collection["Party.IsSuccess"].ToString() == "0" ? false : true;
            }
            if (currentParty.Status == (int)PartyStatus.Closed)
            {
                if (currentParty.IsSuccess)
                {
                    this.scheduleService.ModifyBonus(partyID);
                }
                else
                {
                    this.scheduleService.ResetBonus(partyID);
                }
            }

            if (currentParty.Status == (int)PartyStatus.Cancel)
            {
                this.scheduleService.ResetBonus(partyID);
                this.partyService.BatchQuit(partyID);
            }


            this.partyService.UpdateParty(currentParty);
            //var partyAfterUpdate = this.partyService.GetParty(party.PartyID);
            // return View("Edit",partyAfterUpdate);
            return RedirectToAction("List");
        }

        [HttpPost]
        public ActionResult Cancel(int id)
        {
            var party = this.partyService.GetParty(id);
            party.Status = (int)PartyStatus.Cancel;
            this.partyService.UpdateParty(party);
            var partyAfterUpdate = this.partyService.GetParty(party.PartyID);
            return View("Edit", partyAfterUpdate);
        }

        [HttpPost]
        public ActionResult Quit(int partyID, string accountName, FormCollection collection)
        {
            PartyPageView view = new PartyPageView();
            view.UserName = accountName;
            view.Party = new Party { PartyID = partyID };
            this.partyService.Quit(view);
            var list = this.userService.Participated(partyID, 0, 15);
            return View("_ParticipateList", list);
            // return RedirectToAction("Edit", new { id = partyID });
        }

        [HttpPost]
        public ActionResult RemoveRemark(int? id, int? partyID)
        {
            var remark = this.partyService.GetRemark(id ?? 0);
            if (remark != null)
            {
                this.partyService.RemoveRemark(remark);
            }
            var list = this.partyService.GerRemarkByParty(partyID ?? 0, 0, 15);
            return View("_RemarkList", list);
        }

        [HttpGet]
        public ActionResult Rules()
        {
            BonusRule rule = BonusRuleFactory.GetBonusRuleService();
            return View(rule);
        }

        [HttpPost]
        public ActionResult Rules(BonusRule rule)
        {
            try
            {
                BonusRuleFactory.SetRuleService(rule);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(rule);
            }
            return View();
        }


        [HttpGet]
        public ActionResult AdvMaintain()
        {

            return View();
        }

        [HttpPost]
        public ActionResult BreakApp(int userID, int partyID)
        {

            this.userService.AddAppointment(userID, partyID);
            var list = this.userService.Participated(partyID, 0, 15);
            return View("_ParticipateList", list);
        }

        [HttpGet]
        public ActionResult Modalities()
        {
            ModalityPageView pageView = new ModalityPageView();
            pageView.TypeList = this.partyService.GetPartyType();
            pageView.ModalityList = this.partyService.GetModalityDTO(0, 15);
            return View(pageView);
        }

        [HttpPost]
        public ActionResult AddModality(Modality modality)
        {
            this.partyService.AddModality(modality);
            return RedirectToAction("Modalities");
        }

        [HttpGet]
        public ActionResult Supplieres(int? mid, int? pageIndex)
        {
            SupplierPageView pageView = new SupplierPageView();
            //pageView.Modalities = this.partyService.GetModalityByType(pid ?? 0);
            pageView.Supplier = new Supplier { MID = mid ?? 0 };
            pageView.Supplieres = this.partyService.GetSupplier(mid ?? 0, pageIndex ?? 0, 20);
            return View(pageView);

        }

        [HttpPost]
        public ActionResult AddSupplier(Supplier supplier)
        {
            supplier.CreateDate = DateTime.Now;
            this.partyService.AddSupplier(supplier);
            return RedirectToAction("Supplieres", new { mid = supplier.MID });
        }

        [HttpPost]
        public ActionResult UploadAdv(HttpPostedFileBase uploadFile)
        {

            string[] pathArray = ApplicationSettingsFactory.GetApplicationSettings().AdvPath.Split('\\');
            string fileName = Path.GetFileName(uploadFile.FileName);
            string path = Server.MapPath(pathArray[0] + "/" + pathArray[1] + "/" + fileName);
            path = path.Replace(@"Management\Party\", ""); //path.Remove(path.IndexOf(@"Management\Party\"));
            //uploadFile.SaveAs(path);
            Image.MakeThumbnailImg(uploadFile, path, 960, 80);

            var configuration = WebConfigurationManager.OpenWebConfiguration("/");
            KeyValueConfigurationCollection keyCollection = configuration.AppSettings.Settings;
            KeyValueConfigurationElement element = keyCollection["AdvPath"];
            if (element != null)
            {
                element.Value = pathArray[0] + "\\" + pathArray[1] + "\\" + fileName;
                configuration.Save();
            }

            /*
            string exePath = Server.MapPath("Web.config");
            exePath = exePath.Replace(@"Management\Party\","");
            var configuration = ConfigurationManager.OpenExeConfiguration(exePath);

            KeyValueConfigurationCollection keyCollection = configuration.AppSettings.Settings;
            KeyValueConfigurationElement element = keyCollection["AdvPath"];
            element.Value = pathArray[0] + "\\" + pathArray[1] + "\\" + fileName;

            //configuration.AppSettings.Settings.Remove("AdvPath");
            //configuration.AppSettings.Settings.Add("AdvPath", pathArray[0] + "\\" + pathArray[1] + "\\" + fileName);

            //configuration.Save(ConfigurationSaveMode.Full);
            //configuration.SaveAs(exePath);
            configuration.Save();
            ConfigurationManager.RefreshSection("appSettings");
            */

            return RedirectToAction("AdvMaintain");
        }

        [HttpPost]
        public ActionResult SearchParty(FormCollection collection)
        {
            ViewData["PartyType"] = this.partyService.GetPartyType();
            if (collection["txtID"] != null && !string.IsNullOrEmpty(collection["txtID"]))
            {
                var list = this.partyService.GetParty(int.Parse(collection["txtID"]));
                return View("List", list);
            }
            if (collection["txtPublisher"] != null && !string.IsNullOrEmpty(collection["txtPublisher"]))
            {
                var list = this.partyService.GetPartyByPblish(collection["txtPublisher"], 0, 15);
                return View("List", list);
            }
            if (collection["ddlPartyType"] != null && !string.IsNullOrEmpty(collection["ddlPartyType"]))
            {
                switch (collection["ddlPartyType"])
                {
                    case "0":
                        var list = this.partyService.GetParty(PartyType.Sport, 0, 15);
                        return View("List", list);
                    case "1":
                        var fLit = this.partyService.GetParty(PartyType.Friend, 0, 15);
                        return View("List", fLit);
                    case "2":
                        var htList = this.partyService.GetParty(PartyType.HomeTown, 0, 15);
                        return View("List", htList);
                    case "3":
                        var oList = this.partyService.GetParty(PartyType.Other, 0, 15);
                        return View("List", oList);
                    default:
                        break;
                }

            }
            return RedirectToAction("List");
        }

        [HttpPost]
        public ActionResult RemoveModality(int id)
        {
            this.partyService.RemoveModality(id);
  
            var list = this.partyService.GetModalityDTO(0, 15);
            return View("_ModalityTable",list);
        }

        public ActionResult RemoveSupplier(int id,int? mid)
        {
            this.partyService.RemoveSupplier(id);
            var list = this.partyService.GetSupplier(mid ?? 0, 0, 20);
            return View("_SupplierTable",list);
        }

        [HttpPost]
        public ActionResult RemovePhoto(int paid,int partyID)
        {
            if (Request.IsAjaxRequest())
            {
                this.partyService.DeleteAlbum(paid);
                var list = this.partyService.GetPartyAlbum(partyID, 0, 8);
                return View("_PartyAlbum", list);
            }
            return View();
        }
    }
}
